package com.aurora.oa.work.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.aurora.oa.R;
import com.aurora.oa.activity.BaseActivity;
import com.aurora.oa.application.MyApplication;
import com.aurora.oa.customview.ItemDivider;
import com.aurora.oa.customview.SelectPicPopupWindow;
import com.aurora.oa.message.adapter.ImageSelectAdapter;
import com.aurora.oa.utils.ToastUtil;
import com.aurora.oa.utils.UriUtils;
import com.aurora.oa.work.adapter.AddImageAdapter;
import com.aurora.oa.work.bean.AddExpenceData;
import com.aurora.oa.work.bean.ApplyMoneyData;
import com.aurora.oa.work.presenter.AddExpenceActivityPresenter;
import com.aurora.oa.work.presenter.AddExpenceActivityPresenterImpl;
import com.aurora.oa.work.presenter.ApplyMoneyActivityPresenter;
import com.aurora.oa.work.presenter.ApplyMoneyActivityPresenterImpl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/4/28 0028.
 */
public class ApplyMoneyActivity extends BaseActivity implements ApplyMoneyActivityView{
    private static final int TAKE_PHOTO = 1 ;
    private static final int PICK_PHOTO = 2;
    private List<Uri> imageUri = new ArrayList<>();
    //文件上传成功服务器返回
    private List<String> uploadFileIDs;
    //自定义的弹出框类
    private SelectPicPopupWindow menuWindow;
    private ProgressDialog progressDialog;
    private AddImageAdapter imageSelectAdapter;
    private ApplyMoneyActivityPresenter presenter;
    @Bind(R.id.et_remark)
    EditText etRemark;
    @Bind(R.id.et_content)
    EditText etContent;
    @Bind(R.id.et_money)
    EditText etMoney;
    @Bind(R.id.et_partner)
    EditText etPartner;
    @Bind(R.id.iv_add_img)
    ImageView ivAddImg;
    @Bind(R.id.rv_image)
    RecyclerView rvImage;
    @Bind(R.id.bt_submit)
    Button btSubmit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initTitlebar(true, "添加申请", true);
        setMyContentView(R.layout.activity_apply_money);
        ButterKnife.bind(this);
        initView();
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener(){

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(it, TAKE_PHOTO);
                    break;
                case R.id.btn_pick_photo:
                    Intent local = new Intent();
                    local.setType("image/*");
                    local.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(local, PICK_PHOTO);
                    break;
                default:
                    break;
            }
        }
    };

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch(requestCode) {
                case TAKE_PHOTO:
                    Bundle extras = data.getExtras();
                    Bitmap b = (Bitmap) extras.get("data");
                    String name = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
                    String fileNmae = Environment.getExternalStorageDirectory().toString()+ File.separator+"aurora/image/"+name+".jpg";
                    String srcPath = fileNmae;
                    File myCaptureFile =new File(fileNmae);
                    try {
                        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                            if(!myCaptureFile.getParentFile().exists()){
                                myCaptureFile.getParentFile().mkdirs();
                            }
                            BufferedOutputStream bos;
                            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                            b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                            bos.flush();
                            bos.close();
                            Uri uri = Uri.fromFile(myCaptureFile);
                            imageUri.add(uri);
                            imageSelectAdapter.notifyDataSetChanged();
                            imageSelectAdapter.notifyItemRemoved(imageSelectAdapter.getItemCount());

                        }else{

                            Toast toast= Toast.makeText(ApplyMoneyActivity.this, "保存失败，SD卡无效", Toast.LENGTH_SHORT);
                            toast.show();
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                case PICK_PHOTO:
                    Uri uri = data.getData();
                    imageUri.add(uri);
                    imageSelectAdapter.notifyDataSetChanged();
                    imageSelectAdapter.notifyItemRemoved(imageSelectAdapter.getItemCount());
                    break;
                default:
                    break;
            };
        }
    }

    private void initView() {
        presenter = new ApplyMoneyActivityPresenterImpl(this);
        imageSelectAdapter = new AddImageAdapter(this,imageUri);
        rvImage.setAdapter(imageSelectAdapter);
        rvImage.setLayoutManager(new GridLayoutManager(this,4));
        rvImage.setItemAnimator(new DefaultItemAnimator());
        rvImage.addItemDecoration(new ItemDivider().setDividerWith(3).setDividerColor(Color.TRANSPARENT));
    }

    @OnClick({R.id.iv_add_img, R.id.bt_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_add_img:
                menuWindow = new SelectPicPopupWindow(ApplyMoneyActivity.this, itemsOnClick);
                //显示窗口
                menuWindow.showAtLocation(etContent, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置

                break;
            case R.id.bt_submit:
                presenter.applyMoney();
                break;
        }
    }



    @Override
    public ApplyMoneyData getApplyMoneyData() {
        ApplyMoneyData applyMoneyData = new ApplyMoneyData();
        applyMoneyData.setContent(etContent.getText().toString());
        applyMoneyData.setMoney(etMoney.getText().toString());
        applyMoneyData.setPartner(etPartner.getText().toString());
        applyMoneyData.setRemark(etRemark.getText().toString());
        return applyMoneyData;
    }

    @Override
    public void showProgress() {
        progressDialog = ProgressDialog.show(this,null,"正在发送申请...");
    }

    @Override
    public List<File> getImageFiles() {
        List<File> files = new ArrayList<>();
        for(int i = 0;i<imageUri.size();i++){
            File file =new File(UriUtils.getRealFilePath(this,imageUri.get(i)));
            files.add(file);
        }
        return files;
    }

    @Override
    public void hideProgress() {
        progressDialog.dismiss();
    }

    @Override
    public void onApplyMoneySuccess() {
        ToastUtil.show(this,"提交成功!");
        finish();

    }

    @Override
    public void onApplyMoneyFail(String msg) {
        ToastUtil.show(this,msg);
    }


}
